#!/bin/bash

echo "Executing script by: lichangsheng 24055060132"
echo "-----------------------------------------"

# 设置你的性别（根据实际情况修改为M或F）
MY_GENDER="M"  # 男生请用"M"，女生请用"F"

# 学生文件夹路径
SOURCE_DIR="students"

# 检查目录是否存在
if [ ! -d "$SOURCE_DIR" ]; then
    echo "Error: Directory '$SOURCE_DIR' not found!"
    exit 1
fi

# 进入学生文件夹
cd "$SOURCE_DIR"

# 初始化变量
total_average_score=0.0
student_count=0

# 根据性别设置显示名称
if [ "$MY_GENDER" = "M" ]; then
    gender_full_name="male(M)"
else
    gender_full_name="female(F)"
fi

echo "Calculating average score for all '$MY_GENDER' students..."

# 遍历所有学生文件
for file in *.txt; do
    # 提取文件中的性别
    gender=$(grep "gender:" "$file" | awk '{print $2}')
    
    # 筛选匹配性别的文件
    if [ "$gender" = "$MY_GENDER" ]; then
        # 提取平均分
        average=$(grep "average:" "$file" | awk '{print $2}')
        
        # 累加平均分（处理小数）
        total_average_score=$(echo "scale=2; $total_average_score + $average" | bc)
        student_count=$((student_count + 1))
    fi
done

# 计算最终平均分
final_average=$(echo "scale=1; $total_average_score / $student_count" | bc)

echo "-----------------------------------------"
echo "Total students found: $student_count"
echo "Average score of $gender_full_name: $final_average"
exit 0
